import React from 'react';
import {
  Box, Typography, TextField, Grid, Button,
  Paper, Tabs, Tab, Chip, MenuItem, Select, InputLabel,
  FormControl, IconButton, List, ListItem, ListItemIcon,
  ListItemText, Divider, Table, TableBody, TableCell, TableHead, TableRow,
  Collapse
} from '@mui/material';

import { createTheme, ThemeProvider, CssBaseline } from '@mui/material';
import CalendarTodayIcon from '@mui/icons-material/CalendarToday';
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
import FolderIcon from '@mui/icons-material/Folder';
import DescriptionIcon from '@mui/icons-material/Description';
import LabelIcon from '@mui/icons-material/Label';
import ExpandLess from '@mui/icons-material/ExpandLess';
import ExpandMore from '@mui/icons-material/ExpandMore';

import IndicatorSetting from "./IndicatorSetting"
import { useNavigate } from 'react-router-dom';
const darkTheme = createTheme({
  palette: {
    mode: 'dark',
    background: {
      default: '#0a192f',
      paper: '#112240',
    },
    primary: { main: '#2196f3' },
    success: { main: '#00c853' },
    error: { main: '#f44336' },
    warning: { main: '#ff9800' },
    secondary: { main: '#9c27b0' },
  },
  typography: {
    fontSize: 14,
  },
});
interface TreeNode {
  name: string;
  children?: TreeNode[];
}

const treeData = [
  {
    name: '数据能力域',
    children: [
      {
        name: '数据采集能力',
        children: [
          { name: '数据源覆盖率' },
          { name: '数据采集自动化程度' },
        ],
      },
    ],
  },
  { name: '技术能力域' },
  { name: '业务能力域' },
  { name: '组织能力域' },
];

const flattenTree = (nodes: TreeNode[], parent = ''): { name: string; path: string }[] => {
  return nodes.flatMap((node) => {
    const fullPath = parent ? `${parent} / ${node.name}` : node.name;
    const children = node.children ? flattenTree(node.children, fullPath) : [];
    return [{ name: node.name, path: fullPath }, ...children];
  });
};
/**define page */
const CustomModelEditorPage = () => {
  const [tabIndex, setTabIndex] = React.useState(0);
  const [openMap, setOpenMap] = React.useState({ '数据能力域': true });
  const navigate = useNavigate()
  const handleToggle = (key: any) => {
    setOpenMap((prev) => ({ ...prev, [key]: !prev[key] }));
  };

  const enterIndicatorSetting = ()=>
  {
    navigate('/indicatorSetting')
  }
  const flatData = flattenTree(treeData);

  return (
    <ThemeProvider theme={darkTheme}>
      <CssBaseline />
      <Box sx={{ minHeight: '100vh', backgroundImage: `
            linear-gradient(rgba(10,25,47,0.95), rgba(10,25,47,0.95)),
            repeating-linear-gradient(0deg, transparent, transparent 39px, rgba(255,255,255,0.03) 40px),
            repeating-linear-gradient(90deg, transparent, transparent 39px, rgba(255,255,255,0.03) 40px)`,
        backgroundSize: '40px 40px', p: 3 }}>

        <Typography color="gray" fontSize={14} mb={1}>
          模型管理 / 企业定制模型维护
        </Typography>

        <Grid container spacing={2}>
          <Grid item xs={12} md={4}>
            <Paper sx={{ p: 2, bgcolor: 'rgba(20,35,60,0.8)' }}>
              <Typography variant="h6" color="info.main" gutterBottom>
                🛈 模型基本信息
              </Typography>
              <TextField fullWidth label="模型名称" variant="outlined" size="small" margin="dense" defaultValue="企业数字化转型成熟度评估模型v2.0" />
              <TextField fullWidth multiline rows={3} label="模型描述" variant="outlined" size="small" margin="dense" defaultValue="针对企业数字化转型过程中的能力评估，包含技术、业务、组织等多维度指标..." />
              <Box display="flex" gap={2} mt={1}>
                <TextField label="适用开始日期" type="date" defaultValue="2025-01-01" size="small" fullWidth InputLabelProps={{ shrink: true }} />
                <TextField label="适用结束日期" type="date" defaultValue="2025-12-31" size="small" fullWidth InputLabelProps={{ shrink: true }} />
              </Box>
              <Button startIcon={<CloudUploadIcon />} variant="outlined" fullWidth sx={{ mt: 2, borderColor: 'primary.main' }}>评估标准说明.pdf</Button>
            </Paper>
          </Grid>

          <Grid item xs={12} md={4}>
            <Paper sx={{ p: 2, bgcolor: 'rgba(30,50,80,0.8)' }}>
              <Box display="flex" justifyContent="space-between" alignItems="center" mb={1}>
                <Typography variant="h6" color="warning.main">
                  🧩 能力域与指标体系
                </Typography>
                <Button size="small" variant="contained" onClick={enterIndicatorSetting}>+ 新增</Button>
              </Box>
              <Tabs value={tabIndex} onChange={(e, v) => setTabIndex(v)}>
                <Tab label="树形结构" />
                <Tab label="表格视图" />
              </Tabs>
              {tabIndex === 0 ? (
                <List dense>
                  <ListItem button onClick={() => handleToggle('数据能力域')}>
                    <ListItemIcon><FolderIcon /></ListItemIcon>
                    <ListItemText primary="数据能力域" />
                    {openMap['数据能力域'] ? <ExpandLess /> : <ExpandMore />}
                  </ListItem>
                  <Collapse in={openMap['数据能力域']} timeout="auto" unmountOnExit>
                    <List component="div" disablePadding>
                      <ListItem sx={{ pl:6 }}>
                        <ListItemIcon><LabelIcon color="success" /></ListItemIcon>
                        <ListItemText primary="数据采集能力" />
                      </ListItem>
                      <ListItem sx={{ pl: 6 }}>
                        <ListItemIcon><LabelIcon color="success" /></ListItemIcon>
                        <ListItemText primary="数据源覆盖率" />
                      </ListItem>
                      <ListItem sx={{ pl: 6 }}>
                        <ListItemIcon><LabelIcon color="success" /></ListItemIcon>
                        <ListItemText primary="数据采集自动化程度" />
                      </ListItem>
                    </List>
                  </Collapse>
                  <ListItem>
                    <ListItemIcon><FolderIcon /></ListItemIcon>
                    <ListItemText primary="技术能力域" />
                  </ListItem>
                  <ListItem>
                    <ListItemIcon><FolderIcon /></ListItemIcon>
                    <ListItemText primary="业务能力域" />
                  </ListItem>
                  <ListItem>
                    <ListItemIcon><FolderIcon /></ListItemIcon>
                    <ListItemText primary="组织能力域" />
                  </ListItem>
                </List>
              ) : (
                <Table size="small" sx={{ mt: 1 }}>
                  <TableHead>
                    <TableRow>
                      <TableCell>路径</TableCell>
                      <TableCell>名称</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {flatData.map((row, index) => (
                      <TableRow key={index}>
                        <TableCell>{row.path}</TableCell>
                        <TableCell>{row.name}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              )}
            </Paper>
          </Grid>

          <Grid item xs={12} md={4}>
            <Paper sx={{ p: 2, bgcolor: 'rgba(40,60,90,0.8)' }}>
              <Typography variant="h6" color="orange">📊 评分规则与等级划分</Typography>
              <Tabs value={tabIndex} onChange={(e, v) => setTabIndex(v)} sx={{ mb: 2 }}>
                <Tab label="评分规则" />
                <Tab label="等级划分" />
              </Tabs>
              <FormControl fullWidth size="small" sx={{ mb: 2 }}>
                <InputLabel>评分方式</InputLabel>
                <Select defaultValue="0-5">
                  <MenuItem value="0-5">0-5 分制</MenuItem>
                  <MenuItem value="1-10">1-10 分制</MenuItem>
                </Select>
              </FormControl>
              <TextField fullWidth multiline minRows={4} variant="outlined" label="评分标准说明" defaultValue={`0分：未开展\n1分：初步规划\n2分：部分实施\n3分：基本实施`} />
              <Divider sx={{ my: 2 }} />
              <Typography variant="subtitle1" gutterBottom>成熟度等级划分</Typography>
              <Box display="flex" flexDirection="column" gap={1}>
                <Chip label="初始级：0~1.5 分" color="error" />
                <Chip label="基础级：1.6~2.5 分" color="warning" />
                <Chip label="集成级：2.6~3.5 分" color="primary" />
                <Chip label="优化级：3.6~4.5 分" color="success" />
                <Chip label="引领级：4.6~5 分" color="secondary" />
              </Box>
              <Button fullWidth variant="contained" color="primary" sx={{ mt: 3 }}>保存评分规则配置</Button>
            </Paper>
          </Grid>
        </Grid>
      </Box>
    </ThemeProvider>
  );
};

export default CustomModelEditorPage;
